import {
    LockOutlined,
    UserOutlined,
} from '@ant-design/icons';
import { Alert, message, Typography, Row, Col, Divider, Card, Tag } from 'antd';
import React, { useState, FC, useRef } from 'react';
import { ProFormText, LoginForm, ModalForm, ProFormInstance } from '@ant-design/pro-form';
import { history, Link, useModel, ConnectProps, IndexModelState } from 'umi';

import $utils from '@/utils/utils';
import { login, selectLoginStation } from '@/services/user';

import styles from './index.less';
import { roleNames } from '@/utils/common';


interface PageProps extends ConnectProps {
    index: IndexModelState;
    loading: boolean;
}

const LoginMessage: React.FC<{
    content: string;
}> = ({ content }) => (
    <Alert
        style={{
            marginBottom: 24,
        }}
        message={content}
        type="error"
        showIcon
    />
);

const { Title } = Typography;

let curUserInfo: any = null;

const Login: FC<PageProps> = ({ dispatch, index }) => {

    const chooseFormRef = useRef<ProFormInstance>();
    const [modalVisible, setModalVisible] = useState<boolean>(false);
    const [stationList, setStationList] = useState<any>([]);
    const [userLoginState, setUserLoginState] = useState<API.LoginResult>({});
    const { initialState, setInitialState } = useModel('@@initialState');

    const setUserInfo = async (userInfo: API.CurrentUser) => {
        if (userInfo) {
            await setInitialState((s) => ({
                ...s,
                currentUser: userInfo,
            }));
        }
    };

    // 获取到stationId 跳转首页
    const loginSuccess = async (stationId: any, role: number) => {
        let userInfo = {
            ...curUserInfo,
            stationId: stationId,
            role: role,
        };
        $utils.setStorage('user_info', userInfo, 2 * 3600 * 1000);
        try {
            const msg = await selectLoginStation({});
            if (msg.code === 0) {
                const { sessionId, ...others } = msg.body;
                userInfo = { ...userInfo, ...others };
                $utils.setStorage('user_info', userInfo, 2 * 3600 * 1000);
                await setUserInfo(userInfo);
                /** 此方法会跳转到 redirect 参数所在的位置 */
                if (!history) return;

                const { query } = history.location;
                message.success('登录成功！');
                const { redirect } = query as { redirect: string };
                history.push(redirect || '/');
                return;
            }
        } catch (error) {
            console.log(error);
            message.error('登录失败，请重试！');
        }
    };

    const handleSubmit = async (values: any) => {
        try {
            // 登录
            const msg = await login({ phone: values.phone, password: values.password });
            if (msg.code === 0) {

                const { stationRoleList, ...others } = msg.body;
                curUserInfo = others;
                if (stationRoleList.length > 1) {
                    setStationList(stationRoleList);
                    setModalVisible(true);
                }
                else {
                    loginSuccess(stationRoleList[0].stationId, stationRoleList[0].role);
                }
            }
            // 如果失败去设置用户错误信息
            setUserLoginState(msg);
        } catch (error) {
            console.log(error);
            message.error('登录失败，请重试！');
        }
    };
    const { status, type: loginType } = userLoginState;

    return (
        <div className={styles.container}>
            <div className={styles.content}>
                <div style={{ fontSize: '60px', color: '#fff', marginTop: '4%', marginBottom: '60px' }}>
                    顺畅物流+便利生活
                </div>
                <Row className={styles.Rows} style={{ backgroundColor: '#fff', padding: '40px', maxWidth: '850px' }}>
                    <Col span={12} style={{ display: 'flex', flexDirection: 'column', justifyContent: 'center' }}>
                        <div className={styles.leftLogo}></div>
                    </Col>
                    <Col span={11}>
                        <div style={{ display: 'flex', height: '100%' }}>
                            <Divider className={styles.Dividers} type="vertical" />
                            <div style={{ display: 'flex', flexDirection: 'column', }}>
                                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                                    {/* <img style={{ width: '56px' }} src={logoP} /> */}
                                    <span style={{ fontSize: '30px', color: '333', marginLeft: '6px' }}>小邻工作台</span>
                                </div>
                                <LoginForm
                                    initialValues={{
                                        autoLogin: true,
                                    }}
                                    onFinish={async (values) => {
                                        await handleSubmit(values);
                                    }}
                                >
                                    {status === 'error' && loginType === 'account' && (
                                        <LoginMessage
                                            content={'账户或密码错误'}
                                        />
                                    )}
                                    <>
                                        <ProFormText
                                            name="phone"
                                            fieldProps={{
                                                size: 'large',
                                                prefix: <UserOutlined className={styles.prefixIcon} />,
                                                maxLength: 11
                                            }}
                                            placeholder={'请输入手机号码'}
                                            rules={[
                                                {
                                                    required: true,
                                                },
                                            ]}
                                        />
                                        <ProFormText.Password
                                            name="password"
                                            fieldProps={{
                                                size: 'large',
                                                prefix: <LockOutlined className={styles.prefixIcon} />,
                                                maxLength: 20
                                            }}
                                            placeholder={'请输入密码'}
                                            rules={[
                                                {
                                                    required: true,
                                                },
                                            ]}
                                        />
                                    </>
                                </LoginForm>
                            </div>
                        </div>
                    </Col>
                </Row>
            </div>
            {/* 弹窗选择驿站 */}
            <ModalForm
                title="选择驿站"
                formRef={chooseFormRef}
                visible={modalVisible}
                width={420}
                onVisibleChange={setModalVisible}
                layout={'horizontal'}
                submitter={false}
            >
                {stationList.map((item: any) => {
                    return (
                        <Card key={item.stationId} hoverable={true} onClick={() => {
                            loginSuccess(item.stationId, item.role);
                        }}>
                            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                                <div style={{ flex: 1 }}>
                                    <Title level={5}>{item.stationName}</Title>
                                    <Title level={5} style={{ marginTop: 0 }}>{item.stationAddr}</Title>
                                </div>
                                <div style={{ flex: 0.3, textAlign: 'right' }}>
                                    <Tag color="#108ee9">{roleNames[item.role - 1]}</Tag>
                                </div>
                            </div>
                        </Card>
                    )
                })}

            </ModalForm>
        </div >
    );
};

export default Login;
